package com.tianji.learning.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.db.DbRuntimeException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domin.dto.QuestionFormDTO;
import com.tianji.learning.domin.po.InteractionQuestion;
import com.tianji.learning.domin.po.InteractionReply;
import com.tianji.learning.domin.query.QuestionPageQuery;
import com.tianji.learning.domin.vo.QuestionVO;
import com.tianji.learning.mapper.InteractionQuestionMapper;
import com.tianji.learning.service.IInteractionQuestionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.learning.service.IInteractionReplyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 互动提问的问题表 服务实现类
 * </p>
 *
 * @author 金山
 * @since 2025-10-25
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class InteractionQuestionServiceImpl extends ServiceImpl<InteractionQuestionMapper, InteractionQuestion> implements IInteractionQuestionService {
    private final IInteractionReplyService replyService;
    private final UserClient userClient;

    @Override
    public void saveQuestion(QuestionFormDTO questionFormDTO) {
        //0.内容问题合规性检测

        //1. 数据拷贝
        InteractionQuestion question = BeanUtil.toBean(questionFormDTO, InteractionQuestion.class);
        //2. 补充用户id
        question.setUserId(UserContext.getUser());
        //3. 新增
        this.save(question);

    }

    /**
     * 2.分页查询互动问题列表
     *
     * @param pageQuery
     * @return
     */
    @Override
    public PageDTO<QuestionVO> pageQuery(QuestionPageQuery pageQuery) {
        //1.参数校验
        Long courseId = pageQuery.getCourseId();
        Long sectionId = pageQuery.getSectionId();
        if (ObjectUtil.isEmpty(courseId) && ObjectUtil.isEmpty(sectionId)) {
            throw new DbRuntimeException("课程ID与小节ID不能同时为空");
        }

        //2.分页查询
        Page<InteractionQuestion> pageResult = this.lambdaQuery()
                .select(InteractionQuestion.class, tableFieldInfo -> ObjectUtil.notEqual(tableFieldInfo.getColumn(), "description"))
                .eq(ObjectUtil.isNotEmpty(courseId), InteractionQuestion::getCourseId, pageQuery.getCourseId())
                .eq(ObjectUtil.isNotEmpty(sectionId), InteractionQuestion::getSectionId, pageQuery.getSectionId())
                .eq(pageQuery.getOnlyMine(), InteractionQuestion::getUserId, UserContext.getUser())
                .eq(InteractionQuestion::getHidden, false)
                .page(pageQuery.toMpPageDefaultSortByCreateTimeDesc());
        List<InteractionQuestion> records = pageResult.getRecords();
        if (ObjectUtil.isEmpty(records)) {
            return PageDTO.empty(0L, 0L);
        }
        //3.转换InteractionQuestion转 QuestionVO
        //3.1 收集提问者ID集合，收集最后一次回答ID集合

        //  Set<Long> userIds = records.stream().map(InteractionQuestion::getUserId).collect(Collectors.toSet());
        //  Set<Long> lastAnswerIds = CollStreamUtil.toSet(records, InteractionQuestion::getLatestAnswerId);
        Set<Long> userId = new HashSet<>(records.size());//创建一个Set集合，用于存储用户ID
        Set<Long> lastAnswerId = new HashSet<>(records.size());//创建一个Set集合，用于存储最后一次回答ID
        for (InteractionQuestion record : records) {
            if (!record.getAnonymity()) {
                userId.add(record.getUserId());
            }
            lastAnswerId.add(record.getLatestAnswerId());
        }
        lastAnswerId.remove( null);
        //3.2 根据最后一次回答ID集合 查询 最后一次回答信息，封装成Map（最后一次回答ID，最后一次回答对象)
        List<InteractionReply> lastReplies = replyService.listByIds(lastAnswerId);//批量查询 互动问题的回答或评论
        //CollStreamUtil.toMap(lastReplies, InteractionReply::getId, lastReply -> lastReply);
       // Map<Long, InteractionReply> replyMap = CollStreamUtil.toIdentityMap(lastReplies, InteractionReply::getUserId);//批量查询 互动问题的回答或评论 map  userid：回答或评论
       // Set<Long> replyUserIds = lastReplies.stream().filter(reply -> !reply.getAnonymity()).map(reply -> reply.getUserId()).collect(Collectors.toSet()); //批量查询 互动问题的回答或评论 map  userid：回答或评论 是否匿名
      //  userId.addAll(replyUserIds);//加入回答者ID，

        Map<Long, InteractionReply> replyMap =new HashMap<>(lastReplies.size());
        if (ObjectUtil.isNotEmpty(lastReplies)){
            for (InteractionReply reply : lastReplies) {
                replyMap.put(reply.getId(),reply);
                if(!reply.getAnonymity()){
                    userId.add(reply.getUserId());
                }
            }
        }


        //3.3 根据提问者ID集合 查询 提问者用户信息，封装成Map（用户ID:用户信息对象）
        List<UserDTO> userInfoList = userClient.queryUserByIds(userId);//接上面，前端给的只有提问者
        Map<Long, UserDTO> userInfoMap = new HashMap<>(userInfoList.size());
        if(ObjectUtil.isNotEmpty(userInfoList)) {
            userInfoMap = CollStreamUtil.toIdentityMap(userInfoList, UserDTO::getId);//查询的用户信息（提问者ID:用户信息对象）2号（回答者ID:用户信息对象）
        }
        //4.填补缺少的字段
        ArrayList<QuestionVO> questionVOS = new ArrayList<>(records.size());
        for (InteractionQuestion record : records) {
            //4.1 将po转vo
            QuestionVO vo = BeanUtil.toBean(record, QuestionVO.class);
            //4.2补充提问者信息
            if(!record.getAnonymity()) {
                UserDTO userinfo = userInfoMap.get(record.getUserId());
                if (ObjectUtil.isNotEmpty(userinfo)) {
                    vo.setUserName(userinfo.getName());
                    vo.setUserIcon(userinfo.getIcon());
                }
            }
            //4.3补充最后一次回答信息
            InteractionReply lastReply = replyMap.get(record.getLatestAnswerId());
             if (ObjectUtil.isNotEmpty(lastReply)){
              vo.setLatestReplyContent(lastReply.getContent());
                 UserDTO userDTO = userInfoMap.get(lastReply.getUserId());
                 if (ObjectUtil.isNotEmpty(userDTO)) {
                     vo.setLatestReplyUser(userDTO.getName());
                 }
             }
             //4.4添加到vo集合
            questionVOS.add(vo);
        }
        //5 循环遍历当前页码分页数据，封装vo集合

        //6.返值
        return PageDTO.of(pageResult, questionVOS);
    }
}
